﻿using Coldairarrow.Business.View;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_Manage
{
    public class Base_DepartmentBusiness : BaseBusiness<Base_Department>, IBase_DepartmentBusiness, ITransientDependency

    {
        readonly IOperator _operator;
        public Base_DepartmentBusiness(IDbAccessor db, IOperator @operator, IOperatorDept @odept)
            : base(db)
        {
            _operator = @operator;
            _odept = @odept;
        }
        readonly IOperatorDept _odept;
        #region 外部接口

        public async Task<List<Base_DepartmentTreeDTO>> GetTreeDataListAsync(DepartmentsTreeInputDTO input)
        {
            var where = LinqHelper.True<Base_Department>();
            if (!input.parentId.IsNullOrEmpty()) 
                where = where.And(x => x.ParentId == input.parentId);
            var list = await GetIQueryable().Where(where).ToListAsync();
            var treeList = list.OrderByDescending(m=>m.Sort)
                .Select(x => new Base_DepartmentTreeDTO
                {
                    Id = x.Id,
                    ParentId = x.ParentId,
                    Text = x.Name,
                    Value = x.Id,
                    Sort = x.Sort,
                }).ToList();
        
            return TreeHelper.BuildTree(treeList);
        }

        public async Task<List<Base_DepartmentAnyNoteTreeDTO>> GetWorkshopTreeDataListAsync(DepartmentsTreeInputDTO input)
        {
            //var where = LinqHelper.True<Base_Department>();
            //var list = await GetIQueryable().Where(where).ToListAsync();
            //var treeList = list.OrderByDescending(m => m.Sort)
            //    .Select(x => new Base_DepartmentAnyNoteTreeDTO
            //    {
            //        Id = x.Id,
            //        ParentId = x.ParentId,
            //        Text = x.Name,
            //        Value = x.Id,
            //        Sort = x.Sort,
            //        Type= x.Type.IsNullOrEmpty() ? "": x.Type.ToString()
            //    }).ToList();

            //return TreeHelper.BuildTreeByAnyNode(treeList, input.parentId);
            List<string> liststr = await _odept.GetWorkshopString(input.parentId);
            List<Base_Department> listdata = await Db.GetIQueryable<Base_Department>().Where(x => liststr.Contains(x.Id)).ToListAsync();
            List<Base_DepartmentAnyNoteTreeDTO> listtree = new List<Base_DepartmentAnyNoteTreeDTO>();
            foreach (var item in listdata)
            {
                Base_DepartmentAnyNoteTreeDTO itmetree = new Base_DepartmentAnyNoteTreeDTO();
                itmetree.Id = item.Id;
                itmetree.FullName = item.Name;
                listtree.Add(itmetree);
            }
            return listtree;

            //StringBuilder sql =new StringBuilder();
            //sql.Append("SELECT ");
            //sql.Append("t4.Id,t4.FullName ");
            //sql.Append("FROM (");
            //sql.Append("SELECT ");
            //sql.Append("t1.Id,");
            //sql.Append("IF");
            //sql.Append("( find_in_set( ParentId, @pids ) > 0, @pids := concat( @pids, ',', Id ), 0 ) AS ischild ");
            //sql.Append("FROM ");
            //sql.Append("( SELECT Id, ParentId FROM Base_Department t ORDER BY ParentId, Id ) t1,");
            //sql.Append("( SELECT @pids := '"+input.parentId + "' ) t2");
            //sql.Append(") t3 ");
            //sql.Append("left join Base_Department t4 on t3.Id=t4.Id ");
            //sql.Append("WHERE ischild != 0 ");
            //sql.Append("and (t4.Type=3 or t4.Type=8) ");
            //sql.Append("order by t4.Name");
            //return await Db.GetListBySqlAsync<Base_DepartmentAnyNoteTreeDTO>(sql.ToString());
        }
        public async Task<List<PS_DepartmentDTO>> GetTreeDataListByPrintServiceAsync()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT ");
            sql.Append("Id,");
            sql.Append("ParentId,");
            sql.Append("Name ");
            sql.Append("FROM Base_Department ");
            sql.Append("WHERE ");
            sql.Append("Deleted = 0 ");

            return await Db.GetListBySqlAsync<PS_DepartmentDTO>(sql.ToString());
        }

        public async Task<List<string>> GetChildrenIdsAsync(string departmentId)
        {
            var allNode = await GetIQueryable().Select(x => new TreeModel
            {
                Id = x.Id,
                ParentId = x.ParentId,
                Text = x.Name,
                Value = x.Id
            }).ToListAsync();

            var children = TreeHelper
                .GetChildren(allNode, allNode.Where(x => x.Id == departmentId).FirstOrDefault(), true)
                .Select(x => x.Id)
                .ToList();

            return children;
        }

        public async Task<Base_Department> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        [DataRepeatValidate(new string[] { "Name" }, new string[] { "部门名" })]
        [DataAddLog(UserLogType.部门管理, "Name", "部门名")]
        public async Task AddDataAsync(Base_Department newData)
        {
          
            newData.QrCode = h_Department + "," + newData.Id;
           
            if (newData.Type == 3)
            {
                var deptdata = await _odept.GetOperatorGongChang(newData.ParentId);
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
                PB_Workshop workshop = new PB_Workshop();
                workshop.Id = newData.Id;
                workshop.Code = newData.DeptCode;
                workshop.Name = newData.Name;
             
                workshop.QrCode = h_FWorkshop + "," + workshop.Id;
                workshop.Remarks = "";
                workshop.WorpShopID = newData.Id;
                workshop.CreateTime = new System.DateTime();
                workshop.CreatorId = _operator.UserId;
                workshop.Deleted = false;
                workshop.Latitude = "";
                workshop.Longitude = "";
                workshop.WorkshopLength = 0;
                workshop.WorkshopWidth = 0;
                workshop.WorkshopHeight = 0;
               
                //if (deptdata==null) {
                //    workshop.DeptId = "1468472311458828288";
                //}
                workshop.DeptId = deptdata.DetpId;
                await Db.InsertAsync<PB_Workshop>(workshop);
            }
            await InsertAsync(newData);
           

        }

        [DataRepeatValidate(new string[] { "Name" }, new string[] { "部门名" })]
        [DataEditLog(UserLogType.部门管理, "Name", "部门名")]
        public async Task UpdateDataAsync(Base_Department theData)
        {
            theData.QrCode = h_Department + "," + theData.Id;
            if (theData.Type==3) {
                await ExecuteSqlAsync("update PB_Workshop  SET Name='"+theData.Name+"'  where WorpShopID='" + theData.Id + "'");
            }
            await UpdateAsync(theData);
        }

        [DataDeleteLog(UserLogType.部门管理, "Name", "部门名")]
        public async Task DeleteDataAsync(List<string> ids)
        {
            if (await GetIQueryable().AnyAsync(x => ids.Contains(x.ParentId)))
                throw new BusException("禁止删除！请先删除所有子级！");
    
            var atAllData = Db.GetListBySqlAsync<PB_Workshop>("SELECT  * FROM PB_Workshop  WHERE WorpShopID in (" + String.Join(", ", ids).Replace("\"", "'") + ") ").Result;
            if (atAllData.Count>0) {
                string strid = "";
                foreach (var item in ids)
                {
                    strid += "'" + item + "',";
                }
                strid = strid.Substring(0, strid.Length - 1);
                await ExecuteSqlAsync("delete from PB_Workshop where WorpShopID in (" + strid + ")");
            }
            var baseuserList =await Db.GetIQueryable<Base_User>().Where(m=>ids.Contains(m.DepartmentId)).ToListAsync();
            if (baseuserList.Count>0) {
                throw new BusException("部门下有人员信息禁止删除");
            }
            await DeleteAsync(ids);
        }

        public async Task<List<Base_Department>> GetDataList()
        {
            var q = GetIQueryable().Where(s => s.Type == 1);

            return await q.ToListAsync();
        }

        #endregion
    }
}